<template>
  <div class="menu-management">
    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加菜品
        </el-button>
        <el-button @click="showCategoryDialog = true">
          <el-icon><Menu /></el-icon>
          分类管理
        </el-button>
      </div>
      
      <div class="action-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索菜品名称"
          style="width: 200px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable style="width: 150px">
          <el-option label="全部分类" value="" />
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </div>
    </div>

    <!-- 菜品列表 -->
    <div class="menu-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in filteredMenuItems" :key="item.id">
          <div class="menu-card">
            <div class="menu-image">
              <img :src="item.image" :alt="item.name" />
              <div class="menu-status" :class="item.status">
                {{ item.status === 'available' ? '在售' : '停售' }}
              </div>
            </div>
            
            <div class="menu-content">
              <h4 class="menu-name">{{ item.name }}</h4>
              <p class="menu-description">{{ item.description }}</p>
              <div class="menu-price">¥{{ item.price }}</div>
              <div class="menu-category">{{ getCategoryName(item.categoryId) }}</div>
              
              <div class="menu-actions">
                <el-button size="small" @click="editMenuItem(item)">编辑</el-button>
                <el-button
                  size="small"
                  :type="item.status === 'available' ? 'warning' : 'success'"
                  @click="toggleMenuStatus(item)"
                >
                  {{ item.status === 'available' ? '停售' : '上架' }}
                </el-button>
                <el-button size="small" type="danger" @click="deleteMenuItem(item)">删除</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 添加/编辑菜品对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingItem ? '编辑菜品' : '添加菜品'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜品名称" />
        </el-form-item>
        
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="menuForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="菜品价格" prop="price">
          <el-input-number
            v-model="menuForm.price"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="菜品描述" prop="description">
          <el-input
            v-model="menuForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
        
        <el-form-item label="菜品图片">
          <el-upload
            class="menu-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="menuForm.image" :src="menuForm.image" class="menu-upload-image" />
            <el-icon v-else class="menu-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="销售状态">
          <el-radio-group v-model="menuForm.status">
                  <el-radio value="available">在售</el-radio>
                  <el-radio value="unavailable">停售</el-radio>
                </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMenuItem" :loading="saving">
          {{ editingItem ? '保存修改' : '添加菜品' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog v-model="showCategoryDialog" title="分类管理" width="500px">
      <div class="category-management">
        <div class="add-category">
          <el-input
            v-model="newCategoryName"
            placeholder="请输入分类名称"
            style="width: 200px"
          />
          <el-button type="primary" @click="addCategory">添加分类</el-button>
        </div>
        
        <el-table :data="categories" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="name" label="分类名称" />
          <el-table-column prop="count" label="菜品数量" width="100" />
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button size="small" @click="editCategory(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchKeyword = ref('')
const selectedCategory = ref('')
const showAddDialog = ref(false)
const showCategoryDialog = ref(false)
const editingItem = ref(null)
const saving = ref(false)
const menuFormRef = ref()
const newCategoryName = ref('')

// 菜品表单
const menuForm = reactive({
  name: '',
  categoryId: '',
  price: 0,
  description: '',
  image: '',
  status: 'available'
})

// 表单验证规则
const menuRules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择菜品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' }
  ]
}

// 分类数据
const categories = ref([
  { id: 1, name: '热菜', count: 12 },
  { id: 2, name: '凉菜', count: 8 },
  { id: 3, name: '汤类', count: 6 },
  { id: 4, name: '主食', count: 10 },
  { id: 5, name: '饮品', count: 15 }
])

// 菜品数据
const menuItems = ref([
  {
    id: 1,
    name: '宫保鸡丁',
    categoryId: 1,
    price: 28.0,
    description: '经典川菜，鸡肉嫩滑，花生香脆',
    image: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
    status: 'available'
  },
  {
    id: 2,
    name: '麻婆豆腐',
    categoryId: 1,
    price: 18.0,
    description: '麻辣鲜香，豆腐嫩滑',
    image: 'https://cube.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
    status: 'available'
  },
  {
    id: 3,
    name: '凉拌黄瓜',
    categoryId: 2,
    price: 12.0,
    description: '清爽开胃，夏日必备',
    image: 'https://cube.elemecdn.com/2/21/e571898611a394c7bb1a3b67c9e62jpeg.jpeg',
    status: 'unavailable'
  },
  {
    id: 4,
    name: '西红柿鸡蛋汤',
    categoryId: 3,
    price: 15.0,
    description: '营养丰富，酸甜可口',
    image: 'https://cube.elemecdn.com/1/31/b845bc5c78622e02fdc4d6160a3edpng.png',
    status: 'available'
  }
])

// 过滤后的菜品列表
const filteredMenuItems = computed(() => {
  return menuItems.value.filter(item => {
    const matchKeyword = !searchKeyword.value || 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    const matchCategory = !selectedCategory.value || 
      item.categoryId === selectedCategory.value
    return matchKeyword && matchCategory
  })
})

const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  
  // 模拟上传
  const reader = new FileReader()
  reader.onload = (e) => {
    menuForm.image = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false
}

const editMenuItem = (item) => {
  editingItem.value = item
  Object.assign(menuForm, { ...item })
  showAddDialog.value = true
}

const saveMenuItem = async () => {
  if (!menuFormRef.value) return
  
  try {
    await menuFormRef.value.validate()
    saving.value = true
    
    // 模拟保存API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (editingItem.value) {
      // 编辑
      const index = menuItems.value.findIndex(item => item.id === editingItem.value.id)
      if (index !== -1) {
        menuItems.value[index] = { ...menuForm }
      }
      ElMessage.success('菜品修改成功')
    } else {
      // 添加
      const newItem = {
        ...menuForm,
        id: Date.now()
      }
      menuItems.value.push(newItem)
      ElMessage.success('菜品添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

const toggleMenuStatus = (item) => {
  item.status = item.status === 'available' ? 'unavailable' : 'available'
  ElMessage.success(`菜品已${item.status === 'available' ? '上架' : '停售'}`)
}

const deleteMenuItem = async (item) => {
  try {
    await ElMessageBox.confirm('确定要删除这个菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = menuItems.value.findIndex(i => i.id === item.id)
    if (index !== -1) {
      menuItems.value.splice(index, 1)
      ElMessage.success('菜品删除成功')
    }
  } catch {
    // 用户取消
  }
}

const resetForm = () => {
  editingItem.value = null
  Object.assign(menuForm, {
    name: '',
    categoryId: '',
    price: 0,
    description: '',
    image: '',
    status: 'available'
  })
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
}

const addCategory = () => {
  if (!newCategoryName.value.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  const newCategory = {
    id: Date.now(),
    name: newCategoryName.value,
    count: 0
  }
  categories.value.push(newCategory)
  newCategoryName.value = ''
  ElMessage.success('分类添加成功')
}

const editCategory = (category) => {
  ElMessage.info('编辑分类功能开发中...')
}

const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = categories.value.findIndex(c => c.id === category.id)
    if (index !== -1) {
      categories.value.splice(index, 1)
      ElMessage.success('分类删除成功')
    }
  } catch {
    // 用户取消
  }
}

onMounted(() => {
  console.log('Menu management mounted')
})
</script>

<style lang="scss" scoped>
.menu-management {
  .action-bar {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .action-left {
      display: flex;
      gap: 12px;
    }
    
    .action-right {
      display: flex;
      gap: 12px;
    }
  }
  
  .menu-list {
    .menu-card {
      background: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .menu-image {
        position: relative;
        height: 200px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .menu-status {
          position: absolute;
          top: 10px;
          right: 10px;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          color: white;
          
          &.available {
            background: #67c23a;
          }
          
          &.unavailable {
            background: #f56c6c;
          }
        }
      }
      
      .menu-content {
        padding: 16px;
        
        .menu-name {
          margin: 0 0 8px 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
        
        .menu-description {
          margin: 0 0 12px 0;
          font-size: 14px;
          color: #606266;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .menu-price {
          font-size: 18px;
          font-weight: 600;
          color: #f56c6c;
          margin-bottom: 8px;
        }
        
        .menu-category {
          font-size: 12px;
          color: #909399;
          margin-bottom: 16px;
        }
        
        .menu-actions {
          display: flex;
          gap: 8px;
          
          .el-button {
            flex: 1;
          }
        }
      }
    }
  }
  
  .menu-uploader {
    .menu-upload-image {
      width: 148px;
      height: 148px;
      object-fit: cover;
      border-radius: 6px;
    }
    
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: 0.2s;
      
      &:hover {
        border-color: #409eff;
      }
    }
    
    .menu-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      text-align: center;
      line-height: 148px;
    }
  }
  
  .category-management {
    .add-category {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
}
</style>